package cn.soulic.tools.redis.migration.handler;

import io.lettuce.core.api.sync.RedisCommands;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

/**
 * Hash数据处理
 *
 * @author Soulic Yang
 * @since 1.0.0
 */
public abstract class AbstractHandler implements RedisMigrationHandler {
    public final static String MATCHER_ALL = "*";

    private final Logger logger = LoggerFactory.getLogger(AbstractHandler.class);

    @Resource
    protected RedisCommands<String, String> sourceCommands;

    @Resource
    protected RedisCommands<String, String> targetCommands;

    @Override
    public void handle(String key) {
        doHandle(key);
        doExpire(key);
    }

    /**
     * 数据处理
     *
     * @param key Redis key
     */
    protected abstract void doHandle(String key);

    /**
     * 过期时间处理
     *
     * @param key Redis key
     */
    protected void doExpire(String key) {
        Long ttl = sourceCommands.ttl(key);
        if (ttl != null) {
            if (ttl > 0) {
                sourceCommands.expire(key, ttl);
            } else if (ttl == -2) {
                logger.warn("{} === expiration", key);
            }
        }
    }
}
